/*
 * @Author: your name
 * @Date: 2021-05-12 19:59:05
 * @LastEditTime: 2021-05-13 17:36:22
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \blog-server\routes\login.js
 */
const express = require('express');
const router = express.Router();
const userControl = require('../core/userControl')
const { getUserStatusMsg } = require('../core/statusControl')
const { getPrivateKey } = require('../core/rsaControl')
const jwt = require('jsonwebtoken') //token生成包  JWT
const { encrypt, decrypt } = require('../core/util/util')
const { sendToken } = require('../core/sendToken')
const User = require('../models/User');
const assert = require('http-assert');

router.post('/', async function (req, res, next) {
  let { username, password } = req.body
  try {
    if (!username || username?.trim()?.length === 0 || !password || password?.trim()?.length === 0) {
      assert(false, 422, '账号密码必填')
    }
    const user = await User.findOne({ username }).select('username password')
    //断言检验user
    assert(user, 422, '用户不存在')
    //断言检验密码
    assert.equal(password, decrypt(user.password), 422, '账号密码错误')
    //生成token
    let token = await sendToken(user)
    res.send(200, {
      data: {
        mseeage: '登陆成功',
        data: {
          userId: user._id,
          token: token
        }
      }
    })
  } catch (err) {
    next(err)
  }


  // let result = await userControl.verifyUser(username, pwd)
  // //如果验证账号密码失败
  // if (result.statusCode !== getUserStatusMsg('USER_INN')?.['statusCode']) {
  //   res.send(200, { ...result })
  //   return
  // }
  // console.log(result)
  // //如果验证成功 签发Token
  // if (result.statusCode === '4020' && result.data) {
  //   let token = await sendToken(result)

  //   let backRes = getUserStatusMsg('USER_LOGIN')
  //   backRes.statusCode = 200
  //   res.send(200, {
  //     ...backRes,
  //     data: {
  //       token
  //     }
  //   })
  // }
});



module.exports = router;
